package com.testingedu.jdbcDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.testingedu.db.DBManager;

public class BaseDao<T extends java.io.Serializable> {
	public Connection conn;
	public PreparedStatement ps;
	public ResultSet rs;
	public Class<?> clazz;

	public void close() {
		try {
			if (conn != null) {
				conn.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				ps.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void myJdbcSetValuesAndExecuteSaveOrUpdateOrDelete(String sql,
			List<Object> values) {
		this.myJdbcSetValues(sql, values);
		try {
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void myJdbcSetValuesAndExecuteDelete(String sql, Integer id) {
		List<Object> values = new ArrayList<Object>();
		values.add(id);
		this.myJdbcSetValues(sql, values);
		try {
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void myJdbcSetValuesAndExecuteLoad(String sql, Integer id) {
		List<Object> values = new ArrayList<Object>();
		values.add(id);
		this.myJdbcSetValues(sql, values);
		try {
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void myJdbcSetValuesAndExecuteQuery(String sql, List<Object> values) {
		this.myJdbcSetValues(sql, values);
		try {
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void myJdbcSetValues(String sql, List<Object> values) {
		conn = DBManager.getConnection();
		try {
			ps = conn.prepareStatement(sql);
			int i = 1;
			if (values != null && values.size() > 0) {
				for (Object object : values) {
					if (object instanceof Integer) {
						ps.setInt(i++, (Integer) object);
					} else {
						if (object instanceof String) {
							ps.setString(i++, (String) object);
						} else {
							if (object instanceof Long) {
								ps.setLong(i++, (Long) object);
							} else {
								if (object instanceof Float) {
									ps.setFloat(i++, (Float) object);
								} else {
									if (object instanceof Double) {
										ps.setDouble(i++, (Double) object);
									}
								}
							}
						}
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
